import { _decorator } from "cc";
import { Singleton } from "../decorators/Singleton";
const { ccclass } = _decorator;

type EventCallback = (...args: any[]) => void;

@Singleton
@ccclass("EventManager")
export class EventManager {
  private _eventMap: Map<string, EventCallback[]> = new Map();

  constructor() {}

  public on(eventName: string, callback: EventCallback): void {
    let callbacks = this._eventMap.get(eventName);
    if (!callbacks) {
      callbacks = [];
      this._eventMap.set(eventName, callbacks);
    }
    if (callbacks.indexOf(callback) === -1) {
      callbacks.push(callback);
    }
  }

  public off(eventName: string, callback: EventCallback): void {
    const callbacks = this._eventMap.get(eventName);
    if (callbacks) {
      const index = callbacks.indexOf(callback);
      if (index !== -1) {
        callbacks.splice(index, 1);
      }
      if (callbacks.length === 0) {
        this._eventMap.delete(eventName);
      }
    }
  }

  public emit(eventName: string, ...args: any[]): void {
    const callbacks = this._eventMap.get(eventName);
    if (callbacks) {
      callbacks.forEach((callback) => {
        callback(...args);
      });
    }
  }

  public clear(): void {
    this._eventMap.clear();
  }
}
